﻿namespace Silverlight.Windows
{
    using System;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;

    internal class ModalWindow
    {
        internal static void Show(
            Action onOpen,
            Action onClose,
            Window modalWindow, 
            Window ownerWindow, 
            StartupLocation startupLocation,
            bool showInTaskBar)
        {
            var instance = new ModalWindow();
            instance.Invoke(onOpen, onClose, modalWindow, ownerWindow, startupLocation, showInTaskBar);
        }

        private Action _close = () => { };

        private void Invoke(
            Action onOpen,
            Action onClose,
            Window modalWindow,
            Window ownerWindow,
            StartupLocation startupLocation,
            bool showInTaskBar)
        {
            modalWindow.Closing += WindowClosing;

            onOpen();

            _close = () =>
            {
                modalWindow.Closing -= WindowClosing;
                onClose();
                _close = () => { };
            };

            if (startupLocation == StartupLocation.CenterOwner)
            {
                SetWindowStartupLocationAsCenterOwner(modalWindow, ownerWindow);
            }

            if (showInTaskBar == false)
            {
                var hwnd = Hwnd.FindHwnd(modalWindow);
                Hwnd.RemoveFromTaskBar(hwnd);
            }

            modalWindow.TopMost = true;
            modalWindow.Show();
        }

        private void WindowClosing(object sender, ClosingEventArgs e)
        {
            _close();
        }

        private static void SetWindowStartupLocationAsCenterOwner(Window window, Window ownerWindow)
        {
            window.Left =
                window.Width == 0
                ? ownerWindow.Left + 16
                : ownerWindow.Left + ownerWindow.Width / 2 - window.Width / 2;
            window.Top =
                window.Height == 0
                ? ownerWindow.Top + 16
                : ownerWindow.Top + ownerWindow.Height / 2 - window.Height / 2;
        }
    }
}